<%@ page import="edu.zhku.web4.pojo.User" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="edu.zhku.web4.util.JdbcUtil" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
    <%
        String usernameInput = request.getParameter("username");
        String passwordInput = request.getParameter("pwd1");
        String ageInput = request.getParameter("age");

        User user = null;

        Connection conn = JdbcUtil.getConnection();
        String sql = "SELECT * FROM user WHERE username=?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, usernameInput);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Long userId = rs.getLong("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                Integer age = rs.getInt("age");

                user = new User(userId, username, password, age);
            }
            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (user != null) {
            request.setAttribute("updateMsg", "添加失败，用户名重复");
        } else {
            int res = JdbcUtil.executeUpdate("INSERT INTO user(username, password, age) VALUES (?, ?, ?)", usernameInput, passwordInput, ageInput);
            if (res > 0) {
                request.setAttribute("updateMsg", "添加成功");
            } else {
                request.setAttribute("updateMsg", "添加失败，请重试");
            }
        }
        request.getRequestDispatcher("index.jsp").forward(request, response);

    %>
</body>
</html>
